package action.admin.assignment;

import dao.MngAssignment;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class uploadFinishAssign extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String UPLOAD_DIRECTORY = getServletContext().getRealPath("\\data_finishassign\\");
        String message = "";
        String error = "";
        String name = "";
        String assign_id = "";
        String class_id="";
        try {
            if (ServletFileUpload.isMultipartContent(request)) {
                try {
                    List<FileItem> multiparts;
                    multiparts = new ServletFileUpload(
                            new DiskFileItemFactory()).parseRequest(request);

                    for (FileItem item : multiparts) {
                        if (!item.isFormField()) {
                            name = new File(item.getName()).getName();
                            item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
                        } else {
                            String fieldname = item.getFieldName();
                            String fieldvalue = item.getString();
                            if (fieldname.equals("assign_id")) {
                                assign_id = fieldvalue;
                            } else if (fieldname.equals("class_id")) {
                                class_id = fieldvalue;
                            }
                        }
                    }
                    MngAssignment mngAssign = new MngAssignment();
                    mngAssign.updateFileFinishAss(assign_id, name);
                    //File uploaded successfully
                    message = "File " + name + " Uploaded Successfully";

                } catch (Exception ex) {
                    error = "File " + name + "Upload Failed due to " + ex;
                }
            } else {
                error = "Sorry this Servlet only handles file upload request";
            }
            request.setAttribute("msg", message);
            request.setAttribute("error", error);
            request.setAttribute("class_id", class_id);
            RequestDispatcher rd = request.getRequestDispatcher("student.jsp?page=listAssign");
            rd.forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
